package com.teamclub.app.sconfs.oauth

import com.teamclub.app.sservices.ShiroService
import com.teamclub.domain.system.AppSubjectUser
import org.apache.shiro.authc._
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component

@Component
class OAuth2Realm extends AuthorizingRealm {
  @Autowired
  private var shiroService: ShiroService = _

  override def supports(token: AuthenticationToken): Boolean = token.isInstanceOf[OAuth2Token]

  override def doGetAuthorizationInfo(principals: PrincipalCollection) = {
    val user =  principals.getPrimaryPrincipal.asInstanceOf[AppSubjectUser]
    val userId = user.getId
    val permsSet = shiroService.getUserPermissions(userId)
    val authorInfo = new SimpleAuthorizationInfo
    authorInfo.setStringPermissions(permsSet)
    authorInfo
  }

  override def doGetAuthenticationInfo(token: AuthenticationToken): AuthenticationInfo = {
    val accessToken = token.getPrincipal.asInstanceOf[String]
    val tokenEntity = shiroService.queryByToken(accessToken)
    if(tokenEntity == null || tokenEntity.getExpireTime.getTime < System.currentTimeMillis()) {
      throw new IncorrectCredentialsException("token 失效，请重新登录")
    }
    val user = shiroService.queryUser(tokenEntity.getUserId)
    if(user.getStatus == 0) {
      throw new LockedAccountException("账号已经被锁定，请联系管理员")
    }
    val info = new SimpleAuthenticationInfo(user, accessToken, getName)
    info
  }
}